<?php

namespace app\model;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class RoomSettlement extends Model
{
    protected $table = 'room_settlements';
    
    protected $fillable = [
        'room_id',
        'room_code',
        'room_name',
        'settlement_type',
        'settlement_reason',
        'settlement_time',
        'total_players',
        'total_transactions',
        'total_score',
        'players_data',
        'settlement_strategy',
        'created_by'
    ];

    protected $casts = [
        'room_id' => 'integer',
        'total_players' => 'integer',
        'total_transactions' => 'integer',
        'total_score' => 'integer',
        'created_by' => 'integer',
        'players_data' => 'array',
        'settlement_strategy' => 'array',
        'settlement_time' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 关联房间
     */
    public function room()
    {
        return $this->belongsTo(Room::class, 'room_id');
    }

    /**
     * 关联房间创建者
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }



    /**
     * 创建房间结算汇总记录
     */
    public static function createSettlement($roomId, $settlementType = 'manual', $settlementReason = null)
    {
        $room = Room::find($roomId);
        if (!$room) {
            throw new \Exception('房间不存在');
        }

        // 获取房间用户和交易记录统计
        $roomUsers = RoomUser::where('room_id', $roomId)->get();
        $totalTransactions = AccountingRecord::where('room_id', $roomId)->count();
        
        // 计算每个用户的最终分数
        $userScores = [];
        $totalNetAmount = 0; // 净结算金额（所有正分数的绝对值之和）
        
        foreach ($roomUsers as $roomUser) {
            $userScore = AccountingRecord::where('room_id', $roomId)
                ->where('user_id', $roomUser->user_id)
                ->sum('score');
            
            $userScores[$roomUser->user_id] = $userScore;
            
            // 只计算正分数（赢家的分数）作为净结算金额
            if ($userScore > 0) {
                $totalNetAmount += $userScore;
            }
        }

        // 创建结算汇总记录
        $settlement = self::create([
            'room_id' => $roomId,
            'room_code' => $room->room_code,
            'room_name' => $room->name,
            'settlement_type' => $settlementType,
            'settlement_reason' => $settlementReason,
            'settlement_time' => Carbon::now(),
            'total_players' => $roomUsers->count(),
            'total_transactions' => $totalTransactions,
            'total_score' => $totalNetAmount,
            'created_by' => $room->created_by
        ]);

        // 准备玩家数据
        $playersData = [];
        foreach ($roomUsers as $roomUser) {
            $user = User::find($roomUser->user_id);
            $finalScore = $userScores[$roomUser->user_id] ?? 0;
            
            $playersData[] = [
                'user_id' => $roomUser->user_id,
                'username' => $user ? $user->username : '未知用户',
                'final_score' => (string)$finalScore, // 确保是字符串格式
                'is_winner' => $finalScore > 0,
                'is_room_owner' => $roomUser->user_id == $room->created_by,
                'joined_at' => $roomUser->joined_at ? $roomUser->joined_at->format('Y-m-d H:i:s') : null,
                'left_at' => $roomUser->left_at ? $roomUser->left_at->format('Y-m-d H:i:s') : null,
            ];
        }

        // 生成每个用户的结算策略
        $userStrategies = [];
        foreach ($roomUsers as $roomUser) {
            $userStrategy = \app\service\SettlementStrategyService::generateUserSettlementStrategy($roomUser->user_id, $roomId);
            $userStrategies[$roomUser->user_id] = $userStrategy;
        }
        
        // 生成房间整体最优结算策略
        $roomStrategy = \app\service\SettlementStrategyService::generateOptimalSettlementWithTeaMeal($roomId);
        
        // 更新结算记录，添加整体策略
        $settlement->update([
            'settlement_strategy' => $roomStrategy
        ]);
        
        // 创建结算详情记录
        \app\model\RoomSettlementDetail::createSettlementDetails(
            $settlement->id,
            $roomId,
            $playersData,
            $userStrategies
        );

        // 更新用户的total_score字段
        foreach ($userScores as $userId => $score) {
            $user = User::find($userId);
            if ($user) {
                $user->increment('total_score', $score);
            }
        }

        return $settlement;
    }
}
